<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>问卷管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
      </el-form-item>
      <el-form-item label="" v-for="(filter, index) in searchParams.filters" :key="index">
        <el-input size="small" v-model="filter.fieldValue" v-bind:fieldName="filter.fieldName" v-if="filter.showAble"
                  v-bind:fieldValue="filter.fieldValue" v-bind:compare="filter.compare" :disabled="filter.readonly"
                  @keyup.enter.native="search"
                  :placeholder="filter.placeholder" :readonly="filter.readonly" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
        <el-button size="small" type="primary" icon="el-icon-upload2" @click="toImports()">导入</el-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table size="small" :data="list" highlight-current-row v-loading="loading" border
              element-loading-text="拼命加载中"
              style="width: 100%;" :header-row-style="{width: '100%', color: 'darkorange'}">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="name" label="问卷名称" width="400">
        <template slot-scope="scope">
          <el-link type="primary" @click="toDetail(scope.row)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column sortable prop="projectName" label="所属项目">
      </el-table-column>
      <el-table-column sortable prop="collectNum" label="收集数量" width="100">
      </el-table-column>
      <el-table-column sortable prop="currentNum" label="已收集" width="100">
      </el-table-column>
      <el-table-column sortable prop="collectType.desc" label="收集方式" width="100">
      </el-table-column>
      <el-table-column sortable prop="state.desc" label="问卷状态" width="100">
      </el-table-column>
      <el-table-column sortable prop="pstnNumberApply.desc" label="外呼号码申请状态" width="170">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :icon="'el-icon-video-camera-solid'" :disabled="!showAction('design', scope.row)"
                                @click.native="surveyDesign(scope.$index, scope.row)">设计
              </el-dropdown-item>
              <el-dropdown-item :disabled="!showAction('deploy', scope.row)" :icon="'el-icon-video-play'"
                                @click.native="deploy(scope.$index, scope.row)">发布
              </el-dropdown-item>
              <el-dropdown-item :icon="'el-icon-video-pause'" :disabled="!showAction('pause', scope.row)"
                                @click.native="pause(scope.$index, scope.row)">暂停
              </el-dropdown-item>
              <el-dropdown-item :icon="'el-icon-circle-close'" :disabled="!showAction('end', scope.row)"
                                @click.native="end(scope.$index, scope.row)">归档
              </el-dropdown-item>
              <el-dropdown-item :disabled="!showAction('delete', scope.row)" :icon="'el-icon-delete-solid'"
                                :divided="true" @click.native="deleteItem(scope.$index, scope.row)">删除
              </el-dropdown-item>
              <el-dropdown-item :icon="'el-icon-download'" @click.native="phoneRepository(scope.$index, scope.row)">号码库
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageParams" @callFather="callFather"/>


    <!-- 新增界面 -->
    <el-dialog :title="editTitle" :visible.sync="editFormVisible" :close-on-click-modal="false" width="70%"
               @click='closeDialog("edit")' top="10vh">
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="所属公司" prop="companyName">
          <el-input size="small" disabled v-model="editForm.companyName" placeholder="请输入所属公司"/>
        </el-form-item>
        <el-form-item label="所属项目" prop="projectName">
          <el-autocomplete style="width: 100%" size="small" v-model="editForm.projectName"
                           :fetch-suggestions="querySearchAsync" @select="handleSelect" auto-complete="off"
                           placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="问卷名称" prop="name">
          <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="请输入问卷名称"/>
        </el-form-item>
        <el-form-item label="收集数量" prop="collectNum">
          <el-input size="small" type="number" v-model="editForm.collectNum" auto-complete="off"
                    placeholder="请输入要收集的数量"/>
        </el-form-item>
        <el-form-item label="问卷类型" prop="collectType">
          <el-select size="small" v-model="editForm.collectType" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in [{value: 0, label: '电话问卷'},{value: 1, label: '走访问卷'}]"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="自动外呼" prop="autoCall" v-if="editForm.collectType === 0">
          <el-select size="small" v-model="editForm.autoCall" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in [{value: 1, label: '是'},{value: 0, label: '否'}]"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="外线号码" prop="pstnNumber" v-if="editForm.collectType === 0">
          <el-input size="small" type="number" v-model="editForm.pstnNumber" auto-complete="off"
                    placeholder="请输入外线号码"/>
        </el-form-item>
        <el-form-item label="开场白" prop="startShow">
          <el-input size="small" v-model="editForm.startShow" auto-complete="off" placeholder="请输入备注信息"/>
        </el-form-item>
        <el-form-item label="结束语" prop="endShow">
          <el-input size="small" v-model="editForm.endShow" auto-complete="off" placeholder="请输入备注信息"/>
        </el-form-item>
        <el-form-item label="最大说不清数量" prop="unclearCount">
          <el-input size="small" type="number" v-model="editForm.unclearCount" auto-complete="off"
                    placeholder="请输入最大说不清数量"/>
        </el-form-item>
        <el-form-item label="号码信息模板" prop="endShow">
          <el-input size="small" v-model="editForm.informationTemplate" auto-complete="off"
                    placeholder="请输入号码模板"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitAddForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="导入" width="30%" :visible.sync="uploadDialogFormVisible">
      <div style="text-align: center;">
        <el-upload ref="uploadFile"
                   class="upload-demo"
                   drag
                   accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                   :auto-upload="false"
                   :multiple="false"
                   :action=uploadURL
                   :on-success="uploadSuccess"
                   multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx文件，且不超过500kb</div>
        </el-upload>
        <div slot="footer" class="dialog-footer" style="margin-top: 20px">
          <el-button icon="el-icon-download" @click="toDownLoad">下载模板</el-button>
          <el-button icon="el-icon-upload2" type="primary" @click="submitUpload">立即上传</el-button>
        </div>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {projectList, surveyAdd, surveyDelete, surveyEdit, surveyList} from "../../../api/baseMG";
import Pagination from '../../../components/Pagination'
import {getStore, hasRole} from "../../../utils/util";
import config from "../../../../config/config";

export default {
  data() {
    return {
      uploadURL: config.baseURL + "zsSurvey/upload",
      list: [],
      editFormVisible: false,
      uploadDialogFormVisible: false,
      editTitle: "",
      loading: false,
      editForm: {},
      rules: {
        name: [
          {required: true, message: '请输入问卷名称', trigger: 'blur'}
        ],
        projectName: [
          {required: true, message: '请选择项目', trigger: 'blur'}
        ],
        collectNum: [
          {required: true, message: '请输入收集数量', trigger: 'blur'}
        ],
        collectType: [
          {required: true, message: '请选择问卷类型', trigger: 'blur'}
        ],
        pstnNumber: [
          {required: true, message: '请选输入外线号码', trigger: 'blur'}
        ],
        autoCall: [
          {required: true, message: '请选择是否自动外呼', trigger: 'blur'}
        ]
      },
      // 分页参数
      pageParams: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      searchParams: {
        page: 1,
        perPage: 10,
        filters: [
          {
            showAble: false,
            readonly: true,
            placeholder: "默认",
            fieldName: "companyId",
            compare: "=",
            fieldValue: getStore("userInfo").companyId
          },
          {
            showAble: true,
            readonly: true,
            placeholder: "请输入公司名称",
            fieldName: "companyName",
            compare: "=",
            fieldValue: getStore("userInfo").company
          },
          {
            showAble: true,
            readonly: false,
            placeholder: "请输入项目名称",
            fieldName: "name",
            compare: "like",
            fieldValue: ""
          }
        ],
        isLock: ''
      },
      selectProjectList: [] //备选的项目

    }
  },
  created() {
    this.search();
  },
  // 注册组件
  components: {
    Pagination
  },
  methods: {
    uploadSuccess(response, file, fileList) {
      this.$refs.uploadFile.clearFiles();
      if(response.code === 500) {
        this.$message({
          type: 'error',
          message: response.msg
        });
      }
      if(response.code === 200) {
        this.$message({
          type: 'success',
          message: response.msg
        });
        this.uploadDialogFormVisible = false;
        this.search()
      }
    },
    submitUpload() {
      console.log(this.$refs.uploadFile)
      this.$refs.uploadFile.submit();
    },
    toDownLoad() {
      let a = document.createElement("a"); //创建一个<a></a>标签
      a.href = "/static/templates/导入问卷.xlsx"; // 给a标签的href属性值加上地址，注意，这里是绝对路径，不用加 点.
      a.download = "导入问卷模板.xlsx"; //设置下载文件文件名，这里加上.xlsx指定文件类型，pdf文件就指定.fpd即可
      a.style.display = "none"; // 障眼法藏起来a标签
      document.body.appendChild(a); // 将a标签追加到文档对象中
      a.click(); // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
      a.remove(); // 一次性的，用完就删除a标签
    },
    checkPermission(roles) {
      return hasRole(roles);
    },
    toDetail(item) {
      this.$router.push({path: '/base/survey/detail', query: {id: item.id}})
    },
    phoneRepository(index, row) {
      this.$router.push({path: "/base/repository/index", query: {id: row.id}})
    },
    end(index, row) {
      row.state = 5;
      this.doSurveyEdit(row);
    },
    pause(index, row) {
      row.state = 3;
      this.doSurveyEdit(row);
    },
    deploy(index, row) {
      row.state = 2;
      this.doSurveyEdit(row);
    },
    doSurveyEdit(row) {
      surveyEdit(row).then(resp => {
        if (resp.success) {
          this.$message({
            type: 'success',
            message: resp.msg
          });
          this.search();
        }
      })
    },
    showAction(opt, row) {
      if (opt === 'delete') {
        return row.state.value === 1;
      }
      if (opt === 'template') {
        return row.state.value > 2;
      }
      if (opt === 'deploy') {
        return row.state.value === 1 || row.state.value === 3;
      }
      if (opt === 'design') {
        return row.state.value === 1;
      }
      if (opt === 'pause') {
        return row.state.value === 2;
      }
      if (opt === 'end') {
        return row.state.value === 2 || row.state.value === 3 || row.state.value === 4;
      }
      return false;
    },
    surveyDesign(index, row) {
      this.$router.push({path: "/base/survey/design", query: {id: row.id}})
    },
    handleSelect(item) {
      this.editForm.projectId = item.id;
      this.editForm.projectName = item.name;
    },
    querySearchAsync(queryString, cb) {
      projectList({
        page: 1,
        perPage: 10,
        filters: [
          {fieldName: "companyId", compare: "=", fieldValue: getStore("userInfo").companyId},
          {fieldName: "name", compare: "like", fieldValue: queryString},
        ],
        isLock: ''
      }).then(resp => {
        this.selectProjectList = resp.data.list;
        for (let i = 0; i < this.selectProjectList.length; i++) {
          this.selectProjectList[i].value = this.selectProjectList[i].name;
        }
        cb(this.selectProjectList);
      })
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog === 'edit') {
        this.editFormVisible = false
      } else if (dialog === 'perm') {
        this.dataAccessshow = false
      } else if (dialog === 'unit') {
        this.unitAccessshow = false
      }
    },
    submitAddForm(params) {
      this.$refs[params].validate(valid => {
          if (valid) {
            if (!this.editForm.id) {
              surveyAdd(this.editForm).then(resp => {
                if (resp.success) {
                  this.$message({
                    type: 'success',
                    message: resp.msg
                  });
                  this.editFormVisible = false;
                  this.search();
                }
              })
            } else {
              surveyEdit(this.editForm).then(resp => {
                if (resp.success) {
                  this.$message({
                    type: 'success',
                    message: resp.msg
                  });
                  this.editFormVisible = false;
                  this.search();
                }
              })
            }
          }
        }
      );
    },
    handleAdd() {
      let parse = JSON.parse(getStore("userInfo"));
      this.editTitle = "新增";
      this.editForm = {
        collectType: 0,
        autoCall: 1,
        companyId: parse.companyId,
        companyName: parse.company,
        name: "",
        code: "",
        remark: "",
        projectId: 1
      };
      this.editFormVisible = true
    },
    toImports() {
      this.uploadDialogFormVisible = true;
    },
    // 分页插件事件
    callFather(param) {
      this.searchParams.page = param.currentPage;
      this.searchParams.perPage = param.pageSize;
      this.getList(this.searchParams);
    },
    handleEdit(index, row) {
      this.editTitle = "修改";
      this.editForm = {
        id: row.id,
        companyName: row.companyName ? row.companyName : getStore("userInfo").company,
        companyId: row.companyId ? row.companyId : getStore("userInfo").companyId,
        projectId: row.projectId,
        projectName: row.projectName,
        collectNum: row.collectNum,
        collectType: row.collectType.code,
        endShow: row.endShow,
        startShow: row.startShow,
        unclearCount: row.unclearCount,
        informationTemplate: row.informationTemplate,
        autoCall: row.autoCall.code,
        pstnNumber: row.pstnNumber,
        name: row.name,
        code: row.code,
        remark: row.remark
      };
      this.editFormVisible = true
    },
    search() {
      this.getList(this.searchParams);
    },
    getList(params) {
      this.loading = true;
      surveyList(params).then(resp => {
        if (resp.success) {
          this.loading = false;
          this.list = resp.data.list;
          this.pageParams.currentPage = resp.data.pageNum;
          this.pageParams.pageSize = resp.data.pageSize;
          this.pageParams.total = resp.data.total;
        }
      })
    },
    deleteItem(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        surveyDelete(row.id).then(res => {
          if (res.success) {
            this.$message({
              type: 'success',
              message: res.msg
            });
            this.search(this.formInline)
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
          .catch(err => {
            this.loading = false;
            this.$message.error('删除失败，请稍后再试！')
          })
      })
        .catch(err => {
          console.error(err);
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 25px;
}
</style>
